package com.ztgf.order.service;

import com.ztgf.order.models.dto.OrderReturnCommodityDTO;
import com.ztgf.order.models.dto.OrderStatusDTO;
import com.ztgf.order.models.enums.OrderStateEnum;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ztgf.common.utils.UtilConstants.*;
import static com.ztgf.common.utils.UtilConstants.SIX;

/**
 * @author YUE
 * @create 2020-08-18 18:38
 */
@Slf4j
//@Service
public class DefaultTimerTaskService {

    @DubboReference
    private OrderStatusServiceImpl orderStatusService;
    @DubboReference
    private OrderPayRelationServiceImpl orderPayRelationService;
    @DubboReference
    private OrderReturnCommodityServiceImpl orderReturnCommodityService;
    @Autowired
    private Timer timer;

    private HashMap<String, Timeout> hashMap = new HashMap<>();

    public Map<String, Timeout> getHashMap() {
        return hashMap;
    }

    private final HashMap<String, Timeout> AfterHashMap = new HashMap<>();

    public Map<String, Timeout> getAfterHashMap() {
        return AfterHashMap;
    }

    public void remove(String orderId) {
        Timeout timeout = hashMap.get(orderId);
        timeout.cancel();//停止这个时间轮
        hashMap.remove(orderId + "");//map中去除这条时间轮
    }

    public void removeAfter(String orderId) {
        Timeout timeout = AfterHashMap.get(orderId);
        if (timeout == null) {
            return;
        }
        timeout.cancel();//停止这个时间轮
        hashMap.remove(orderId);//map中去除这条时间轮
    }

    public void createAfterOrderCountDown(int time, String orderId) {
        TimerTask timerTask = new AfterDefaultTimerTask(orderId);
        Timeout timeout = timer.newTimeout(timerTask, time, TimeUnit.DAYS);
        AfterHashMap.put(orderId, timeout);
    }

    /**
     * 添加进时间轮
     *
     * @param time    定时时间(天)
     * @param orderId 订单id
     */
    public void createOrderCountDown(int time, String orderId) {
        TimerTask timerTask = new DefaultTimerTask(orderId);
        Timeout timeout = timer.newTimeout(timerTask, time, TimeUnit.DAYS);
        hashMap.put(orderId, timeout);
    }


    private class DefaultTimerTask implements TimerTask {
        private final DateTimeFormatter F = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        private String orderId;
        private long timestamp;

        public DefaultTimerTask(String orderId) {
            this.orderId = orderId;
            this.timestamp = System.currentTimeMillis();
        }

        @Override
        public void run(Timeout timeout) {
            log.info(String.format("任务执行时间:%s,订单异常时间:%s,订单ID:%s",
                    LocalDateTime.now().format(F), LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()).format(F), orderId));
            //处理订单逻辑
            //改变订单状态
            OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(Long.parseLong(orderId));
            if (orderStatusDTO.getOrderState() == OrderStateEnum.ORDER_STATE_ENUM_WAIT_SIGN.getCode()) {
                orderStatusDTO.setOrderState(OrderStateEnum.ORDER_STATE_ENUM_SIGNED.getCode());
                orderPayRelationService.thawOrderLastMoney(Long.parseLong(orderId));//解冻资金
                orderStatusService.updateById(orderStatusDTO);
                return;
            }
            orderStatusDTO.setIsExpiration(1);//设置订单已经过期
            orderStatusService.updateById(orderStatusDTO);
            hashMap.remove(orderId);//map中去除这条时间轮
        }
    }

    private class AfterDefaultTimerTask implements TimerTask {
        private final DateTimeFormatter F = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        private String orderId;
        private long timestamp;

        public AfterDefaultTimerTask(String orderId) {
            this.orderId = orderId;
            this.timestamp = System.currentTimeMillis();
        }

        @Override
        public void run(Timeout timeout) {
            log.info(String.format("任务执行时间:%s,售后订单:%s,售后订单id:%s",
                    LocalDateTime.now().format(F), LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()).format(F), orderId));
            OrderReturnCommodityDTO returnCommodityDTO = orderReturnCommodityService.selectById(Long.valueOf(orderId));
            if (returnCommodityDTO.getShipState() == THREE) {
                OrderReturnCommodityDTO updateDTO = new OrderReturnCommodityDTO();
                updateDTO.setId(returnCommodityDTO.getId());
                updateDTO.setShipState(FIVE);//买家已签收
                orderReturnCommodityService.updateById(updateDTO);
                return;
            }
            if (returnCommodityDTO.getShipState() == FOUR) {
                OrderReturnCommodityDTO updateDTO = new OrderReturnCommodityDTO();
                updateDTO.setId(returnCommodityDTO.getId());
                updateDTO.setShipState(SIX);//6卖家已签收
                orderReturnCommodityService.updateById(updateDTO);
                return;
            }
            AfterHashMap.remove(orderId);//map中去除这条时间轮
        }
    }



}
